<template>
	<view class="payment-container">
		<!-- 订单信息 -->
		<view class="order-info">
			<view class="order-header">
				<text class="order-title">订单支付</text>
				<text class="order-number">订单号：{{ orderNumber }}</text>
			</view>
			<view class="payment-amount">
				<text class="amount-label">支付金额</text>
				<text class="amount-value">¥{{ paymentAmount.toFixed(2) }}</text>
			</view>
		</view>

		<!-- 支付方式 -->
		<view class="payment-methods">
			<view class="method-title">选择支付方式</view>
			<view class="method-item selected">
				<image src="/static/images/wechat-pay.png" class="method-icon"></image>
				<text class="method-name">微信支付</text>
				<text class="method-check">✓</text>
			</view>
		</view>

		<!-- 支付状态 -->
		<view v-if="paymentStatus" class="payment-status">
			<view v-if="paymentStatus === 'paying'" class="status-paying">
				<image src="/static/images/loading.gif" class="loading-icon"></image>
				<text class="status-text">支付处理中，请稍候...</text>
			</view>
			<view v-else-if="paymentStatus === 'success'" class="status-success">
				<text class="success-icon">✓</text>
				<text class="status-text">支付成功</text>
			</view>
			<view v-else-if="paymentStatus === 'failed'" class="status-failed">
				<text class="failed-icon">✗</text>
				<text class="status-text">支付失败，请重试</text>
			</view>
		</view>

		<!-- 支付按钮 -->
		<view class="payment-actions">
			<button 
				v-if="!paymentStatus || paymentStatus === 'failed'" 
				class="pay-btn" 
				@click="startPayment"
				:disabled="paying"
			>
				{{ paying ? '支付中...' : `立即支付 ¥${paymentAmount.toFixed(2)}` }}
			</button>
			<button 
				v-else-if="paymentStatus === 'success'" 
				class="success-btn" 
				@click="goToOrderDetail"
			>
				查看订单
			</button>
		</view>

		<!-- 支付说明 -->
		<view class="payment-tips">
			<text class="tips-title">支付说明</text>
			<text class="tips-item">• 请在15分钟内完成支付，超时订单将自动取消</text>
			<text class="tips-item">• 支付成功后，我们将尽快为您安排发货</text>
			<text class="tips-item">• 如有疑问，请联系客服</text>
		</view>
	</view>
</template>

<script>
import { post, get, showLoading, hideLoading } from '@/utils/request.js'

export default {
	data() {
		return {
			orderId: null,
			orderNumber: '',
			paymentAmount: 0,
			paymentStatus: null, // null, 'paying', 'success', 'failed'
			paying: false,
			statusCheckTimer: null
		}
	},
	onLoad(options) {
		this.orderId = options.orderId;
		this.orderNumber = options.orderNumber;
		this.paymentAmount = parseFloat(options.amount) || 0;

		// 检查订单支付状态
		this.checkPaymentStatus();
	},
	onUnload() {
		// 清理定时器
		if (this.statusCheckTimer) {
			clearInterval(this.statusCheckTimer);
		}
	},
	methods: {
		// 检查支付状态
		async checkPaymentStatus() {
			try {
				const res = await get(`/miniapp/orders/${this.orderId}/payment-status`);
				const status = res.data.status;
				
				if (status === 'processing' || status === 'shipped' || status === 'completed') {
					this.paymentStatus = 'success';
				} else if (status === 'cancelled') {
					this.paymentStatus = 'failed';
				}
			} catch (error) {
				console.error('检查支付状态失败:', error);
			}
		},

		// 开始支付
		async startPayment() {
			if (this.paying) return;

			try {
				this.paying = true;
				this.paymentStatus = 'paying';
				showLoading('创建支付订单...');

				// 创建微信支付订单
				const payRes = await post(`/miniapp/orders/${this.orderId}/pay`);
				
				// 检查是否已经支付成功
				if (payRes.data.payment_status === 'paid') {
					hideLoading();
					this.paymentStatus = 'success';
					uni.showToast({
						title: '订单已支付成功',
						icon: 'success'
					});
					return;
				}
				
				const paymentData = payRes.data.payment_data;
				hideLoading();

				// 调用微信支付
				console.log('支付参数:', paymentData);

				// 检查是否是模拟支付模式
				if (paymentData.mockMode || paymentData.error) {
					console.log('检测到模拟支付模式，直接模拟支付成功');
					this.handleMockPaymentSuccess();
					return;
				}

				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: paymentData.timeStamp,
					nonceStr: paymentData.nonceStr,
					package: paymentData.package,
					signType: paymentData.signType,
					paySign: paymentData.paySign,
					totalFee: Math.round(this.paymentAmount * 100).toString(), // 金额转换为分，必须是字符串
					success: (res) => {
						console.log('支付成功:', res);
						this.paymentStatus = 'success';
						this.handleRealPaymentSuccess(res);
					},
					fail: (err) => {
						console.error('支付失败:', err);
						if (err.errMsg.includes('cancel')) {
							this.paymentStatus = null;
							uni.showToast({
								title: '支付已取消',
								icon: 'none'
							});
						} else {
							this.paymentStatus = 'failed';
							uni.showToast({
								title: '支付失败',
								icon: 'none'
							});
						}
					}
				});

			} catch (error) {
				console.error('创建支付订单失败:', error);
				this.paymentStatus = 'failed';
				uni.showToast({
					title: error.message || '支付失败',
					icon: 'none'
				});
			} finally {
				this.paying = false;
				hideLoading();
			}
		},

		// 处理模拟支付成功
		async handleMockPaymentSuccess() {
			try {
				showLoading('处理支付结果...');
				// 调用模拟支付成功接口
				await post(`/miniapp/orders/${this.orderId}/mock-pay-success`);
				this.paymentStatus = 'success';
				hideLoading();
				uni.showToast({
					title: '支付成功',
					icon: 'success'
				});
			} catch (error) {
				console.error('模拟支付处理失败:', error);
				this.paymentStatus = 'failed';
				hideLoading();
				uni.showToast({
					title: '支付处理失败',
					icon: 'none'
				});
			}
		},

		// 处理真实支付成功
		async handleRealPaymentSuccess(paymentResult) {
			try {
				showLoading('确认支付结果...');
				// 调用确认支付接口
				await post(`/miniapp/orders/${this.orderId}/confirm-payment`, {
					transaction_id: paymentResult.transactionId || paymentResult.transaction_id
				});
				this.paymentStatus = 'success';
				hideLoading();
				uni.showToast({
					title: '支付成功',
					icon: 'success'
				});
			} catch (error) {
				console.error('确认支付失败:', error);
				hideLoading();
				// 如果确认失败，启动状态检查作为备用方案
				this.startStatusCheck();
			}
		},

		// 处理支付成功（备用方法）
		handlePaymentSuccess() {
			this.startStatusCheck();
		},

		// 开始状态检查
		startStatusCheck() {
			// 每2秒检查一次支付状态
			this.statusCheckTimer = setInterval(async () => {
				try {
					const res = await get(`/miniapp/orders/${this.orderId}/payment-status`);
					const status = res.data.status;

					if (status === 'processing' || status === 'shipped' || status === 'completed') {
						this.paymentStatus = 'success';
						clearInterval(this.statusCheckTimer);
						this.statusCheckTimer = null;
					}
				} catch (error) {
					console.error('检查支付状态失败:', error);
				}
			}, 2000);

			// 30秒后停止检查
			setTimeout(() => {
				if (this.statusCheckTimer) {
					clearInterval(this.statusCheckTimer);
					this.statusCheckTimer = null;
				}
			}, 30000);
		},

		// 跳转到订单详情
		goToOrderDetail() {
			uni.redirectTo({
				url: `/pages/order/detail?id=${this.orderId}`
			});
		}
	}
}
</script>

<style scoped>
.payment-container {
	background-color: #F5F5F5;
	min-height: 100vh;
	padding-bottom: 120rpx;
}

.order-info {
	background-color: #FFFFFF;
	margin: 20rpx;
	border-radius: 16rpx;
	padding: 40rpx 30rpx;
}

.order-header {
	margin-bottom: 30rpx;
}

.order-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333333;
	display: block;
	margin-bottom: 12rpx;
}

.order-number {
	font-size: 24rpx;
	color: #999999;
}

.payment-amount {
	text-align: center;
	padding: 30rpx 0;
	border-top: 1rpx solid #F0F0F0;
}

.amount-label {
	font-size: 28rpx;
	color: #666666;
	display: block;
	margin-bottom: 12rpx;
}

.amount-value {
	font-size: 48rpx;
	font-weight: bold;
	color: #D4AF37;
}

.payment-methods {
	background-color: #FFFFFF;
	margin: 20rpx;
	border-radius: 16rpx;
	padding: 30rpx;
}

.method-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
	margin-bottom: 20rpx;
}

.method-item {
	display: flex;
	align-items: center;
	padding: 20rpx;
	border: 2rpx solid #E0E0E0;
	border-radius: 12rpx;
}

.method-item.selected {
	border-color: #D4AF37;
	background-color: #FFF9E6;
}

.method-icon {
	width: 48rpx;
	height: 48rpx;
	margin-right: 16rpx;
}

.method-name {
	flex: 1;
	font-size: 28rpx;
	color: #333333;
}

.method-check {
	color: #D4AF37;
	font-size: 32rpx;
	font-weight: bold;
}

.payment-status {
	background-color: #FFFFFF;
	margin: 20rpx;
	border-radius: 16rpx;
	padding: 40rpx 30rpx;
	text-align: center;
}

.status-paying, .status-success, .status-failed {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.loading-icon {
	width: 80rpx;
	height: 80rpx;
	margin-bottom: 20rpx;
}

.success-icon {
	width: 80rpx;
	height: 80rpx;
	line-height: 80rpx;
	text-align: center;
	font-size: 60rpx;
	color: #52C41A;
	background-color: #F6FFED;
	border-radius: 50%;
	margin-bottom: 20rpx;
}

.failed-icon {
	width: 80rpx;
	height: 80rpx;
	line-height: 80rpx;
	text-align: center;
	font-size: 60rpx;
	color: #FF4D4F;
	background-color: #FFF2F0;
	border-radius: 50%;
	margin-bottom: 20rpx;
}

.status-text {
	font-size: 28rpx;
	color: #666666;
}

.payment-actions {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #FFFFFF;
	padding: 20rpx 40rpx 40rpx;
	box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.pay-btn, .success-btn {
	width: 100%;
	border: none;
	border-radius: 50rpx;
	padding: 30rpx;
	font-size: 32rpx;
	font-weight: bold;
}

.pay-btn {
	background-color: #D4AF37;
	color: #FFFFFF;
}

.pay-btn:disabled {
	background-color: #CCCCCC;
}

.pay-btn:active:not(:disabled) {
	background-color: #B8941F;
}

.success-btn {
	background-color: #52C41A;
	color: #FFFFFF;
}

.success-btn:active {
	background-color: #389E0D;
}

.payment-tips {
	background-color: #FFFFFF;
	margin: 20rpx;
	border-radius: 16rpx;
	padding: 30rpx;
}

.tips-title {
	font-size: 28rpx;
	font-weight: bold;
	color: #333333;
	margin-bottom: 16rpx;
	display: block;
}

.tips-item {
	font-size: 24rpx;
	color: #666666;
	line-height: 1.6;
	margin-bottom: 8rpx;
	display: block;
}

.tips-item:last-child {
	margin-bottom: 0;
}
</style>
